package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.common.utils.RandomUtils;
import com.sangmo.fts.process.storage.interfaces.CsfRepaymentCreation;
import com.sangmo.fts.process.storage.model.CsfAgreement;
import com.sangmo.fts.process.storage.model.CsfLoan;
import com.sangmo.fts.process.storage.model.CsfRepayment;
import com.sangmo.fts.process.storage.repo.CsfRepaymentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class CsfRepaymentEntityService extends AuthorityEntityService<CsfRepayment> {

    @Autowired
    private CsfRepaymentRepo csfRepaymentRepo;

    @Autowired
    private CsfLoanService csfLoanService;

    @Autowired
    private CsfAgreementService csfAgreementService;

    @Override
    protected IDataViewRepo<CsfRepayment> getRepo() {
        return csfRepaymentRepo;
    }

    @Override
    protected void onCreate(CsfRepayment entity, Object bo) {
        super.onCreate(entity, bo);
        entity.setCode(RandomUtils.generateRandomNum(12));
        CsfRepaymentCreation creation = (CsfRepaymentCreation) bo;
        CsfLoan loan = csfLoanService.get(creation.getLoanId());
        entity.setPayId(loan.getApplyId());
        entity.setBankId(loan.getBankId());
        CsfAgreement agreement = csfAgreementService.findByContractId(loan.getContractId());
        entity.setAgreementId(agreement.getId());
    }

    @Override
    protected void afterCreated(CsfRepayment entity, Object bo) {
        super.afterCreated(entity, bo);
        List<CsfRepayment> repaymentList = csfRepaymentRepo.findByLoanId(entity.getLoanId());
        BigDecimal totalPaymentAmount = BigDecimal.ZERO;
        for (CsfRepayment repayment : repaymentList) {
            totalPaymentAmount = totalPaymentAmount.add(repayment.getAmount());
        }
        totalPaymentAmount = totalPaymentAmount.add(entity.getAmount());
        csfLoanService.settle(entity.getId(), totalPaymentAmount);
    }
}
